package com.tpfinal.agenda.core.mysqlrequests;

import java.sql.SQLException;
import java.util.Map;

import com.tpfinal.agenda.controller.MainController;
import com.tpfinal.agenda.core.AgendaActionParamsCodes;
import com.tpfinal.agenda.core.AgendaActionsIDs;
import com.tpfinal.agenda.model.Company;
import com.tpfinal.agenda.model.Contact;
import com.tpfinal.agenda.model.Person;

public class UpdateContactRequest extends MySqlBaseRequest {

	private static final String QUERY = "UPDATE contactos SET %s='%s', %s='%s', %s='%s', %s=%s, %s=%s, %s='%s', %s=%s, %s=%s, %s='%s', %s='%s' WHERE %s=%s";
	private Contact contact;

	@Override
	public int getID() {
		return AgendaActionsIDs.UPDATE_CONTACT;
	}

	@Override
	protected void setup(Map<String, Object> params) {
		this.queryType = QUERY_TYPE_UPDATE;

		contact = (Contact) params.get(AgendaActionParamsCodes.PARAM_CONTACT);

		String type = null;
		String name = contact.getName();
		String address = contact.getAddress();
		int zip = contact.getCityInfo().getZip();
		int phone = contact.getPhone();
		String email = contact.getEmail();
		String birthday = null;
		int cellphone = 0;
		String url = null;
		String businessSector = null;

		if (contact instanceof Person) {
			type = MySQL.MYSQL_CONTACT_TYPE_PERSON;
			birthday = String.format("'%s'",
					((Person) contact).getBirthdayAsString());
			cellphone = ((Person) contact).getCellphone();

		} else {
			type = MySQL.MYSQL_CONTACT_TYPE_COMPANY;
			url = ((Company) contact).getUrl();
			businessSector = ((Company) contact).getBusinessSector();
		}

		this.sqlQuery = String.format(QUERY, MySQL.MYSQL_COLUMN_TIPO, type,
				MySQL.MYSQL_COLUMN_NOMBRE_RAZON, name,
				MySQL.MYSQL_COLUMN_DIRECCION, address, MySQL.MYSQL_COLUMN_CP,
				zip, MySQL.MYSQL_COLUMN_TELEFONO, phone,
				MySQL.MYSQL_COLUMN_EMAIL, email,
				MySQL.MYSQL_COLUMN_TELEFONO_MOVIL, cellphone,
				MySQL.MYSQL_COLUMN_FECHA_NACIMIENTO, birthday,
				MySQL.MYSQL_COLUMN_WEB, url, MySQL.MYSQL_COLUMN_RUBROS,
				businessSector, MySQL.MYSQL_COLUMN_ID, contact.getId());

		System.out.println(this.sqlQuery);
	}

	@Override
	protected Map<String, Object> processResult(Map<String, Object> resultSet) {

		try {

			MainController controller = MainController.get();
			controller.getContactsList()
					.remove(controller.getSelectedContact());
			controller.getContactsList().add(contact);
			controller.setSelectedContact(contact);

			connection.close();

			resultSet.put(RESULT_CODE, OK);
		} catch (SQLException e) {
			e.printStackTrace();
			resultSet.put(RESULT_CODE, ERROR);
		}

		return resultSet;

	}

}
